package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.mapper.DtsAdminMapper;
import com.qf.mapper.DtsBrandMapper;
import com.qf.pojo.DtsAdmin;
import com.qf.service.AdminService;
import com.qf.util.bcrypt.BCryptPasswordEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
@Service
public class AdminServiceimpl implements AdminService {

    @Autowired
    DtsAdminMapper adminMapper;
    @Autowired
    DtsBrandMapper brandMapper;

    @Override
    public List<DtsAdmin> findAdmin(String name) {
        QueryWrapper<DtsAdmin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",name);
        queryWrapper.eq("deleted",false);
        List<DtsAdmin> list = adminMapper.selectList(queryWrapper);

        return list;
    }

    @Override
    public void insert(DtsAdmin admin) {

        admin.setAddTime(new Date());
        admin.setUpdateTime(new Date());
        admin.setDeleted(false);


        //设置密码为密文
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(admin.getPassword());

        admin.setPassword(encode);
        //新增
        adminMapper.insert(admin);

         int result = adminMapper.insert(admin);

    }

    @Override
    public void update(DtsAdmin admin) {
        QueryWrapper wrapper = new QueryWrapper();

        wrapper.eq("deleted",false);
        adminMapper.updateById(admin);
    }

    @Override
    public void delete(DtsAdmin admin) {

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("admin_id",admin.getId());
        wrapper.eq("deleted",false);
        int count = brandMapper.selectCount(wrapper);
        if(count!=0){
            throw new RuntimeException("该管理员被品牌关联，不能删除!!");
        }
        admin.setDeleted(true);
       adminMapper.updateById(admin);
    }

    @Override
    public List<DtsAdmin> selectAdmin() {
        QueryWrapper wrapper = new QueryWrapper();

        wrapper.like("role_ids","4");

        List list = adminMapper.selectList(wrapper);
        return list;
    }
}
